<template>
  <div>
    <!-- 标题 -->
    <!-- <div class="new-title">添加字段</div> -->
    <!-- 转换名称 -->
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" class="demo-ruleForm">
      <div>
        <el-form-item
          label="转换名称"
          prop="name"
          label-width="110px"
          class="new-text-left title-input"
        >
          <el-input v-model="ruleForm.name" clearable @input="setName"></el-input>
        </el-form-item>
      </div>
      <!-- 表格 -->
      <div class="table-wrap">
        <el-table :data="ruleForm.tableData" border stripe style="width: 100%">
          <el-table-column type="index" label="序号" width="180" align="center"></el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="字段中文名称" width="180" align="left">
            <template slot="header">
              <i class="color-red">*</i>字段中文名称
            </template>
            <template slot-scope="scope">
              <span v-if="!scope.row.isedit||getReadOnlyFlag">{{ scope.row.logicColumnChineseName }}</span>
              <el-form-item
                v-else
                :prop="`tableData.${scope.$index}.logicColumnChineseName`"
                :rules="tableRules.logicColumnChineseName"
              >
                <el-input v-model="scope.row.logicColumnChineseName" @change="isUpdateForm = true"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="字段英文名称" align="left" width="200">
            <template slot="header">
              <i class="color-red">*</i>字段英文名称
            </template>
            <template slot-scope="scope">
              <span v-if="!scope.row.isedit||getReadOnlyFlag">{{ scope.row.logicColumnName }}</span>
              <el-form-item
                v-else
                :prop="`tableData.${scope.$index}.logicColumnName`"
                :rules="tableRules.logicColumnName"
              >
                <el-input v-model="scope.row.logicColumnName" @input="vaildEnName"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="字段类型" align="left" width="180">
            <template slot="header">
              <i class="color-red">*</i>字段类型
            </template>
            <template slot-scope="scope">
              <span v-if="!scope.row.isedit||getReadOnlyFlag">{{ scope.row.logicColumnType }}</span>
              <el-form-item
                v-else
                :prop="`tableData.${scope.$index}.logicColumnType`"
                :rules="tableRules.logicColumnType"
              >
                <el-select
                  v-model="scope.row.logicColumnType"
                  placeholder="请选择"
                  @change="isUpdateForm = true"
                >
                  <el-option
                    v-for="item in getDictionaryList.ColumnType"
                    :key="item.dataValue"
                    :label="item.dataName+'('+item.dataValue+')'"
                    :value="item.dataValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="logicColumnLength"
            label="字段长度"
            align="left"
          >
            <template slot-scope="scope">
              <span v-if="!scope.row.isedit||getReadOnlyFlag">{{ scope.row.logicColumnLength }}</span>
              <el-form-item
                v-if="scope.row.isedit"
                :prop="`tableData.${scope.$index}.logicColumnLength`"
                :rules="tableRules.logicColumnLength"
              >
                <el-input v-model="scope.row.logicColumnLength" @change="isUpdateForm = true"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="添加规则" align="center">
            <template slot-scope="scope">
              <span v-if="!scope.row.isedit||getReadOnlyFlag">{{ scope.row.rule }}</span>
              <el-form-item
                v-if="scope.row.isedit"
                :prop="`tableData.${scope.$index}.rule`"
                :rules="tableRules.rule"
              >
                <el-input v-model="scope.row.rule" class="new-input" disabled></el-input>
                <el-tooltip
                  v-if="scope.row.isedit"
                  class="item"
                  effect="light"
                  content="修改"
                  placement="top"
                >
                  <i class="iconfont icon-xiugaibianji" @click.stop="edit(scope.$index, scope.row)"></i>
                </el-tooltip>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!getReadOnlyFlag" align="center" label="操作">
            <template slot="header" slot-scope="scope">
              操作
              <i class="iconfont icon-tianjia" @click.stop="add"></i>
            </template>
            <template slot-scope="scope">
              <el-form-item>
                <el-tooltip
                  v-if="scope.row.isedit"
                  class="item"
                  effect="light"
                  content="删除"
                  placement="top"
                >
                  <i class="iconfont icon-shanchu" @click.stop="del(scope.$index, scope.row)"></i>
                </el-tooltip>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <!-- 规则弹框 -->
    <el-dialog
      title="添加规则"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      append-to-body
      :close-on-click-modal="false"
    >
      <span>
        <!-- 内容区域 -->
        <div class="new-flex">
          <!-- 树结构 -->
          <div class="content-child">
            <div class="line-flex">
              <div style="width:90px">函数搜索：</div>
              <el-input v-model="filterTextNo" clearable placeholder="输入关键字进行过滤">
                <i slot="suffix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </div>
            <el-tree
              ref="treeNo"
              clearable
              class="filter-tree"
              :data="dataNo"
              :props="defaultProps"
              default-expand-all
              :filter-node-method="filterNodeNo"
              @node-click="changeClick"
            >
              <span slot-scope="{ node,data }" class="custom-tree-node">
                <el-tooltip class="item" effect="dark" placement="top">
                  <div slot="content" v-html="data.funcDoc" v-if="data.funcDoc"></div>
                  <div slot="content" v-else>{{ node.label }}</div>
                  <span>{{ node.label }}</span>
                </el-tooltip>
              </span>
            </el-tree>
          </div>
          <!-- 表格结构 -->
          <div class="content-child">
            <div class="line-flex">
              <div style="width:90px">字段搜索：</div>
              <el-input v-model="keyword" clearable placeholder="请输入搜索的字段名称">
                <i slot="suffix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </div>
            <el-table :data="currentData" border height="260" style="width: 100%" stripe>
              <el-table-column prop="logicColumnName" label="字段名称" align="center">
                <template scope="scope">
                  <div @click="tdWord(scope.row.logicColumnName)">{{ scope.row.logicColumnName }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="logicColumnType" label="字段类型" align="center">
                <template scope="scope">
                  <div @click="tdWord(scope.row.logicColumnName)">{{ scope.row.logicColumnType }}</div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- 文本框 -->
        <div class="textarea-warp">
          <div class="new-title">编辑：</div>
          <el-input
            v-model.trim="textarea"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            @blur="getWord($event)"
            @input="Sync"
          ></el-input>
        </div>
      </span>
      <span slot="footer" class="dialog-footer">
        <span>
          <el-button @click="validateExpression">校 验</el-button>
        </span>
        <span>
          <el-button @click="handleCloseAll">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </span>
    </el-dialog>
    <el-dialog title="校验返回信息" :visible.sync="dialogVisible2" width="50%" append-to-body>
      <span>{{ vaildResult }}</span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from "vuex";

export default {
  data() {
    const validatePass = (rule, value, callback) => {
      const reg = /^[\u4E00-\u9FA5]+$/;
      if (!value) {
        callback(new Error("请输入字段中文名称"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入中文格式"));
      } else {
        callback();
      }
    };
    const blurText = async (rule, value, callback) => {
      const boolean = new RegExp("^[,0-9]*$").test(value); // console.log(boolean)[，,0-9]*
      if (!boolean && value !== "") {
        callback(new Error("请输入数字"));
      }
    };
    return {
      isUpdateForm: false,
      validFlag: false,
      index: "",
      newid: "",
      start: "",
      end: "",
      dialogData: [],
      currentData: [],
      dataNo: [],
      filterTextNo: "",
      keyword: "",
      textarea: "",
      textareaarr: [],
      dialogVisible: false,
      dialogVisible2: false,
      vaildResult: "",
      ruleForm: {
        name: "",
        tableData: [],
        flag: false
      },
      tableRules: {
        logicColumnChineseName: [
          {
            required: true,
            message: "请输入字段中文名称",
            trigger: ["blur", "change"]
          }
        ],
        logicColumnName: [
          {
            required: true,
            message: "请输入字段英文名称",
            trigger: "blur"
          },
          {
            max: 30,
            message: "不超过30个字符",
            trigger: "blur"
          },
          {
            pattern: /^[a-zA-Z]+[_a-zA-Z0-9]*$/g,
            message: "英文、数字、下划线组合，英文开头",
            trigger: "blur"
          }
        ],
        logicColumnType: [
          {
            required: true,
            message: "请选择字段类型",
            trigger: ["blur", "change"]
          }
        ],
        logicColumnLength: [
          {
            required: false,
            message: "请输入字段长度"
          },
          { validator: blurText, trigger: "blur" }
        ],
        rule: [
          {
            required: true,
            message: "请选择规则",
            trigger: "change"
          }
        ]
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入转换名称",
            trigger: ["blur", "change"]
          }
        ]
      },
      defaultProps: {
        children: "children",
        label: "functionNameEn"
      },
      options: [], // 字段类型
      persentViewFoot: {},
      isLink: false
    };
  },
  watch: {
    filterTextNo(val) {
      this.$refs.treeNo.filter(val);
    },
    keyword(val) {
      this.currentData = this.dialogData.filter(
        item => item.logicColumnName.indexOf(val) !== -1
      );
      console.log(this.currentData, "匹配");
    },
    textarea(val) {
      this.validFlag = false;
    }
  },
  mounted() {
    this.$store.commit("setDelFlag", false);
    this.persentViewFoot = JSON.parse(JSON.stringify(this.getViewFoot));
    this.dialogData = JSON.parse(
      JSON.stringify(this.getSubmitInfo[this.getViewFoot.preNode].outPut)
    );
    this.currentData = JSON.parse(JSON.stringify(this.dialogData));
    this.initOpera();
  },
  computed: {
    ...mapGetters([
      "getDictionaryList",
      "getViewFoot",
      "getOperatorInfo",
      "getSubmitInfo",
      "getReadOnlyFlag",
      "getDelFlag"
    ]),
    flowList() {
      return this.$store.state.flow.flowList;
    },
    flag() {
      return this.$store.state.flow.flag;
    }
  },
  destroyed() {
    if (this.isLink && this.isUpdateForm) {
      this.$alert("当前内容有变更，需重连下一节点才生效", "提示", {
        confirmButtonText: "确定"
      });
    }
    // 如果是删除节点禁止触发销毁钩子
    if (this.getDelFlag) {
      this.$store.commit("setDelFlag", false);
    } else {
      const ids = this.persentViewFoot.id; // id
      const value = this.ruleForm; // 对象
      const obj = {};
      obj[ids] = value;
      this.$store.commit("setOperatorInfo", obj); // 将对象存入store，kye-value形式
      // 存放本算子信息，最终提交用
      const submitIds = this.persentViewFoot.id; // id
      // 根据节点id匹配节点坐标
      const arr = this.flowList.nodeList.filter(
        item => this.persentViewFoot.id === item.id
      );
      const submitValue = {
        operateName: this.ruleForm.name,
        operateType: "2",
        location: `${arr[0].top},${arr[0].left}`,
        orderNumber: this.persentViewFoot.id,
        outPut: this.ruleForm.tableData
      };
      const submitObj = {};
      submitObj[submitIds] = submitValue;
      this.$store.commit("setSubmitInfo", submitObj);
    }
  },
  methods: {
    ...mapMutations("flow", ["setNodeName"]),
    // 存放算子信息
    operator() {
      return this.ruleForm;
    },
    handleClose(done) {
      this.filterTextNo = "";
      done();
    },
    handleCloseAll() {
      this.filterTextNo = "";
      this.dialogVisible = false;
    },
    // 如果存在算子信息那么页面进来加载算子信息
    // 若没有算子信息那么执行初始化
    initOpera() {
      if (this.getViewFoot.nextNode) {
        this.isLink = true;
      } else {
        this.isLink = false;
      }
      if (
        this.getOperatorInfo[this.getViewFoot.id] &&
        this.getOperatorInfo[this.getViewFoot.id].flag
      ) {
        this.ruleForm = JSON.parse(
          JSON.stringify(this.getOperatorInfo[this.getViewFoot.id])
        );
      } else {
        // const obj = Object.assign(this.getViewFoot, { flag: true })
        this.ruleForm.flag = true;
        this.ruleForm.name = this.getViewFoot.name;
        if (
          this.$store.state.tree.readOnlyFlag &&
          this.getSubmitInfo[this.getViewFoot.id]
        ) {
          this.ruleForm.tableData = JSON.parse(
            JSON.stringify(this.getSubmitInfo[this.getViewFoot.id].outPut)
          );
        } else {
          this.ruleForm.tableData = JSON.parse(
            JSON.stringify(this.getSubmitInfo[this.getViewFoot.preNode].outPut)
          );
          this.ruleForm.tableData.forEach(item => {
            item.rule = item.logicColumnName;
          });
        }
      }
    },
    setName() {
      this.$store.state.flow.flag = true;
      const data = {
        name: this.ruleForm.name,
        id: this.getViewFoot.id,
        that: this
      };
      this.setNodeName(data);
      this.$store.state.flow.flag = false;
    },
    vaildEnName(val) {
      this.isUpdateForm = true;
      if (this.ruleForm.tableData.length > 0) {
        for (let i = this.ruleForm.tableData.length - 1; i >= 0; i--) {
          const tempStr = this.ruleForm.tableData[i].logicColumnName;
          for (let j = 0; j < i; j++) {
            if (
              tempStr.toUpperCase() ===
              this.ruleForm.tableData[j].logicColumnName.toUpperCase()
            ) {
              this.$alert(
                `<p>第${i +
                  1}行，字段英文名称${tempStr.toUpperCase()}重复，请修改</p>\n`,
                "信息",
                {
                  dangerouslyUseHTMLString: true,
                  confirmButtonText: "确定",
                  customClass: "tip-map-info",
                  type: "warning",
                  callback: action => {
                    return false;
                  }
                }
              );
              this.ruleForm.tableData[i].logicColumnName = "";
              return false;
            }
          }
        }
      }
    },
    getWord(e) {
      this.start = e.target.selectionStart;
      this.end = e.target.selectionEnd;
      console.log(this.end, "看结果", e);
    },
    tdWord(val) {
      if (this.end > 0) {
        this.textarea = this.changeStr(
          this.textarea,
          this.start,
          this.end,
          val
        );
      } else {
        this.textareaarr.push(val);
        const arr = this.textareaarr.filter(s => s && s.trim());
        this.textarea = arr.toString().replace(/,/g, "");
      }
    },
    changeStr(str, index, end, changeStr) {
      this.end = 0;
      return str.substr(0, index) + changeStr + str.substr(end);
    },
    Sync(val) {
      this.textareaarr = [val];
    },
    add() {
      const obj = {
        logicColumnChineseName: "",
        logicColumnLength: "",
        logicColumnName: "",
        logicColumnType: "",
        rule: "",
        isedit: true
      };
      this.ruleForm.tableData.push(obj);
    },
    del(index, row) {
      this.$confirmBox("删除").then(() => {
        this.ruleForm.tableData.splice(index, 1);
      });
    },
    edit(index, row) {
      this.dialogVisible = true;
      this.index = index;
      this.textarea = row.rule;
      this.getAllExpression();
    },
    submit() {
      if (this.validFlag) {
        this.isUpdateForm = true;
        this.ruleForm.tableData[this.index].rule = this.textarea;
        this.dialogVisible = false;
        this.filterTextNo = "";
        this.textarea = "";
        this.textareaarr = [];
      } else {
        this.$message({ message: "请先进行校验", type: "warning" });
      }
    },
    // 获取规则列表
    async getAllExpression() {
      const res = await this.$api.home.getAllExpression();
      if (res.data.resultCode === 0) {
        const arr = res.data.data;
        this.dataNo = [];
        for (const i in arr) {
          const obj = {
            functionNameEn: i,
            children: arr[i]
          };
          this.dataNo.push(obj);
        }
      }
    },
    // 校验规则
    async validateExpression() {
      if (!this.textarea) {
        this.$message({ message: "请输入校验规则", type: "warning" });
      } else {
        const arr = [];
        this.dialogData.forEach(item => {
          const obj = {};
          (obj.fieldFormat = item.sourceTimeFormat),
            (obj.fieldLength = Number(item.logicColumnLength)),
            (obj.fieldName = item.logicColumnName),
            (obj.fieldType = item.logicColumnType);
          arr.push(obj);
        });

        const params = {
          expression: this.textarea,
          inputFormat: arr
        };
        const res = await this.$api.home.validateExpression(params);
        this.vaildResult = res.data.resultMessage;
        if (res.data.resultCode === 0) {
          this.validFlag = true;
          this.$message({ message: "校验成功", type: "success" });
        } else {
          this.$message({ message: "校验失败", type: "error" });
          this.dialogVisible2 = true;
        }
      }
    },
    filterNodeNo(value, data) {
      if (!value) return true;

      return data.functionNameEn.indexOf(value) !== -1;
    },

    submitForm() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    changeClick(val) {
      this.tdWord(val.defaultExpression);
    }
  },
  components: {}
};
</script>

<style lang='scss' scoped>
.new-input {
  width: 60%;
}
.add-foot {
  text-align: right;
  margin-top: 20px;
}
.new-title {
  // color: #0090ff;
  font-size: 16px;
  margin-bottom: 10px;
}
.new-scroll {
  overflow: auto;
  height: 200px;
  flex: 1;
}
.iconfont {
  color: #0090ff;
  font-size: 14px;
  cursor: pointer;
}
.color-red {
  color: #f56c6c;
  margin-right: 5px;
}
.new-flex {
  display: flex;
  justify-content: space-between;
}
.content-child {
  width: 49%;
  height: 300px;

  .filter-tree {
    overflow: auto;
    height: 260px;
  }
}
.textarea-warp {
  margin-top: 40px;
}
.new-del {
  .cell {
    padding-bottom: 20px;
  }
}
/deep/ {
  .el-tree {
    .el-tooltip.item {
      display: inline-block;
      width: 350px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .el-tree-node__expand-icon {
      color: #0090ff;
      font-size: 14px;
    }
    .el-tree-node__expand-icon.is-leaf {
      color: transparent;
    }
  }

  .title-input {
    width: 360px;
  }
  .el-table .el-input__inner {
    height: 32px;
    line-height: 32px;
  }
  .el-select {
    width: 100%;
  }
  .table-wrap {
    .el-table__body-wrapper td {
      padding-bottom: 0;
      padding-top: 5px;
    }
    .el-table .el-form-item {
      margin-bottom: 16px;
    }
    .el-table .el-form-item__error {
      transform: scale(0.9);
      padding-top: 0;
    }
  }
  .el-dialog .el-table {
    border-top: 0;
  }
  .el-dialog__header {
    display: flex;
    .el-dialog__title {
      color: #0090ff;
    }
  }
  .dialog-footer {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
  }
  .el-dialog__body {
    padding: 30px 40px;
  }
  .el-input {
    .el-input__suffix-inner {
      color: #0090ff;
      font-size: 15px;
    }
    .el-icon-search {
      float: right;
    }
  }
}
.el-form-item {
  margin-top: 0.16rem;
}
</style>
